<script setup>
import { find, pick } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks.js';
import { useGlobalState } from '@/store/globalState';
import { useDictLists, useResetForm } from '@/hooks/tool.js';
import { getRiskType, getRiskList, addRisk, updateRisk, delRisk } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';
import { TableList } from '@/components/MainComponents.js';
import DataImport from '@/components/DataImport/index.vue';
import RiskInfoModal from '@/views/components/RiskInfoModal.vue';

const uploadUrl = useGlobalState().globalState.fileUrl + '/energyservice/library/importRisk';
const riskModal = ref(null);
const modalStatus = ref('新增');
const queryForm = ref(null);
const riskCascader = ref(null);
const queryParams = ref({
  riskLevel1: null, //一级风险id
  riskLevel2: null, //二级风险id
  riskLevel3: null, //三级
  riskType: null, //风险分类（字典risk_type）
  pageNum: 1,
  pageSize: 10,
});
const selCascader = ref([]);
const cascaderProps = ref({
  emitPath: true,
  checkStrictly: true,
  label: 'name',
  value: 'id',
});
const riskInfo = ref(null);
const dictLists = useDictLists(['risk_type']);
const handleEdit = (row, $index) => {
  modalStatus.value = '编辑';
  riskInfo.value = pick(row, [
    'riskId',
    'riskLevel1',
    'riskLevel2',
    'riskLevel3',
    'riskType',
    'riskDescribe',
    'controlTarget',
    'controlMethod',
    'controlActivity',
  ]);
  riskModal.value.open = true;
};
const handleDelete = (row, $index) => {
  MessageBox.confirm('是否确认要删除？', '删除', { type: 'warning' })
    .then(() => {
      runDel(row.riskId);
    })
    .catch(() => {});
};
const columnObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'riskDescribe',
      label: '风险描述',
      width: '',
      align: 'center',
    },
    {
      slotName: 'riskType',
      label: '风险分类',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'riskLevel1Content',
      label: '一级风险等级类型',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'riskLevel2Content',
      label: '二级风险等级类型',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'riskLevel3Content',
      label: '三级风险等级类型',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'controlTarget',
      label: '控制目标',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'controlMethod',
      label: '控制措施',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'controlActivity',
      label: '控制活动',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'operationTime',
      label: '操作时间',
      width: '',
      align: 'center',
    },
    {
      label: '操作',
      width: '',
      align: 'center',
      operations: [
        {
          type: 'text',
          label: '编辑',
          buttonClick: handleEdit,
        },
        {
          type: 'text',
          label: '删除',
          buttonClick: handleDelete,
        },
      ],
    },
  ],
});

const [cascaderList, ,] = useRequest(getRiskType, {
  defaultParams: [{}],
  // onSuccess: res => {
  //   cascaderList.value = map(res.data, v => (v.children = v?.children?.length ? v.children : null));
  // },
});
const [tableData, loading, runTable] = useRequest(getRiskList, {
  defaultParams: [queryParams.value],
  debounceInterval: 300,
});
const [, , runAdd] = useRequest(addRisk, {
  manual: true,
  onSuccess: res => {
    Message.success(res.msg);
    handleQuery();
  },
});
const [, , runEdit] = useRequest(updateRisk, {
  manual: true,
  onSuccess: res => {
    Message.success(res.msg);
    handleQuery();
  },
});
const [, , runDel] = useRequest(delRisk, {
  manual: true,
  onSuccess: res => {
    Message.success(res.msg ?? '删除成功');
    handleQuery();
  },
});

const getList = e => {
  queryParams.value.pageNum = e.page;
  queryParams.value.pageSize = e.limit;
  runTable(queryParams.value);
};
const handleChange = value => {
  if (value.length) {
    queryParams.value.riskLevel1 = value[0];
    queryParams.value.riskLevel2 = value?.[1] ?? null;
    queryParams.value.riskLevel3 = value?.[2] ?? null;
  } else {
    queryParams.value.riskLevel1 = null;
    queryParams.value.riskLevel2 = null;
    queryParams.value.riskLevel3 = null;
  }
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  runTable(queryParams.value);
};
const resetQuery = () => {
  useResetForm(queryForm);
  riskCascader.value.panel.clearCheckedNodes();
  handleQuery();
};
const handleAdd = () => {
  modalStatus.value = '新增';
  riskModal.value.open = true;
};
const handleSubmit = params => {
  if (modalStatus.value === '新增') runAdd(params);
  if (modalStatus.value === '编辑') runEdit(params);
};
const handleUpload = () => {
  handleQuery();
};
</script>

<template>
  <div class="app-container">
    <div class="u-p20 u-base-fg">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="风险等级类型">
          <el-cascader
            ref="riskCascader"
            v-model="selCascader"
            :props="cascaderProps"
            :options="cascaderList"
            clearable
            placeholder="请选择风险等级类型"
            size="small"
            style="width: 360px"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="风险分类" prop="riskType">
          <el-select
            class="el-input_search"
            v-model="queryParams.riskType"
            placeholder="请选择风险分类"
            clearable
            size="small"
            style="width: 200px"
          >
            <el-option
              v-for="dict in dictLists?.risk_type ?? []"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="u-p20 u-base-fg u-mt20">
      <div class="u-df-spb u-mb20">
        <span class="u-prim-text u-fs16">风险库</span>
        <div class="u-df-st">
          <el-button type="primary" plain size="small" @click="handleAdd">新增</el-button>
          <DataImport
            :onlyShowBtn="true"
            :showIcon="false"
            :showTemDownload="false"
            :uploadUrl="uploadUrl"
            impText="上传文件"
            title="风险信息"
            class="u-ml10"
            @handleFileSuccess="handleUpload"
          />
        </div>
      </div>
      <TableList
        v-loading="loading"
        :tableData="tableData?.rows ?? []"
        :columObj="columnObj"
        :pageObj="queryParams"
        :total="tableData?.total ?? 0"
        :height="600"
        @getList="getList"
      >
        <template v-slot:riskType="{ scope }">
          {{ find(dictLists?.risk_type, item => item.dictValue === scope.row.riskType)?.dictLabel }}
        </template>
      </TableList>
    </div>
    <RiskInfoModal
      ref="riskModal"
      :status="modalStatus"
      :cascaderList="cascaderList"
      :riskTypeList="dictLists?.risk_type ?? []"
      :riskInfo="riskInfo"
      @submit="handleSubmit"
    />
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 0;
}
</style>
